/*****************
* Ant Scriptdef/Javascript routine for resolving dependencies in runtine
*
* @version 0.1
* @author Arnoud ten Hoedt / Roonaan
*********************/

// Import Java Classes
importClass(java.io.File);
importClass(java.lang.System);
importClass(java.net.URL);
importClass(java.io.FileWriter);


// Attribute fetching
var dir = attributes.get("dir"),
    type = attributes.get("type"),
    url = attributes.get("url"),
    mirrorfile = attributes.get("mirrorfile");
    
if(!type) {
	type = "http";
}
// Internal processing variables
var bForce = "true".equalsIgnoreCase(attributes.get("force"));
var fDir = new File(dir);
var bImport = false;
var fImported = new File(dir + "/ant.imported.log");
// Processing flow
if(fImported.exists()) {
  bImport = bForce;
} else {
  bImport = true;
}

if(bImport) {
	if(mirrorfile) {
		var mirror_file = File.createTempFile("ant4web", "ant");
		var gettask = project.createTask("get");
		gettask.setSrc(new URL(mirrorfile));
		gettask.setDest(mirror_file);
		gettask.execute();
		importClass(java.io.File);
		importClass(javax.xml.parsers.DocumentBuilder);
		importClass(javax.xml.parsers.DocumentBuilderFactory);
		
  		var mirror_dbf = DocumentBuilderFactory.newInstance();
  		var mirror_db = mirror_dbf.newDocumentBuilder();
  		var mirror_document = mirror_db.parse(mirror_file);
  		
  		mirror_document.getDocumentElement().normalize();
  		
  		mirror_nodes = mirror_document.getElementsByTagName("mirror");
  		
  		var random = Math.floor(Math.random() * mirror_nodes.length);
  		
  		self.log("Number of mirror urls: " + mirror_nodes.length);		
  		var mirror_url = mirror_nodes.item(random).getAttribute("url");
  		self.log("Randomly selected: " + random + " -> " + mirror_url);
  		
		delete mirror_nodes;
		delete mirror_document;
		delete mirror_db;
		url =  mirror_url;
	}
	self.log("Resolving " + type + "-dependency at " + url);
	var ok = false;
	switch(true) {
		case "svn".equalsIgnoreCase(type):
			self.log("Preparing for subversion download");
			ok = dependency_get_svn(attributes);
			break;
		case "http".equalsIgnoreCase(type):
			self.log("Preparing for http download");
			ok = dependency_get_http(attributes);
			break;
		default:
			self.log("Unsupported dependency type '" + type + "'");
	}
	if(ok) {
		var f = new FileWriter(fImported);
		f.write("ant.imported at " + (new Date()).toString());
		f.close();
	}
}


function dependency_get_svn(attr) {
	var task = project.createTask("exec");
	task.setExecutable("svn");
	argCmd = task.createArg(); argCmd.setValue("export");
	argUrl = task.createArg(); argUrl.setValue(attr.get("url"));
	argDir = task.createArg(); argDir.setValue(attr.get("dir"));
	task.perform();
	return true;
}

function dependency_get_http(attr) {
	var dir = new File(attr.get("dir"));
	if(!dir.exists() && !dir.mkdirs()) {
		self.log("Unable to create directory " + dir);
		return false;
	}
	var task = project.createTask("get");
	var fTempFile = File.createTempFile("ant4web","ant");
	var fUnzip = new File(fTempFile.toString() + "-unpacked");
	self.log("Temporary Download File: " + fTempFile);
	var url = new URL(attr.get("url"))
	task.setSrc(url);
	task.setDest(fTempFile);
	task.perform();
	
	// Prepare fileset for copying expanded package
	var fs = project.createDataType("fileset");
	if(attr.get("expandbase")) {
		fs.setDir(new File(fUnzip.toString() + "/" + attr.get("expandbase")));
	} else {
		fs.setDir(new File(fUnzip.toString()));
	}
	fs.setIncludes("**");
	
	var expand = attr.get("expand");
	
	// Expand package
	if("tgz".equalsIgnoreCase(expand)) {
		fUnzip.mkdirs();
		var untar = project.createTask("untar");
		untar.setSrc(fTempFile);
		
		importClass(org.apache.tools.ant.taskdefs.Untar);
		
		var mtd = new Untar.UntarCompressionMethod();
		mtd.setValue("gzip");
		
		untar.setCompression(mtd);
		untar.setDest(fUnzip);
		untar.execute();
	} else if("zip".equalsIgnoreCase(expand)) {
		fUnzip.mkdirs();
		var unzip = project.createTask("unzip");
		unzip.setSrc(fTempFile);
		unzip.setDest(fUnzip);
		unzip.execute();
	} else {
		self.log(null == expand ? "@expand is required" : "@expand=" + expand + " is currently not supported");
	}
	
	// Copy expanded files to final location
	var cp = project.createTask("copy");
	cp.setTodir(new File(attr.get("dir")));
	cp.addFileset(fs);
	cp.execute();
	
	var del = project.createTask("delete");
	del.setDir(fUnzip);
	del.execute();
	
	return true;
}